package com.ChefApp.mobile;

import java.io.InputStream;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class main extends Activity {
    /** Called when the activity is first created. */
	Intent arch_intent;
	DailyPreview dailyReceipe;
	TextView title, tvZutaten, tvTitle, tvSubTitle, tvZubereitung;
	TableRow tr;
	ImageView preImage, ivRec;
	Button bZutaten, bZubereitung, buttonUmr, button;
	EditText suche;
	Receipe recDay;
	Vorschau[] df;
	Intent intent,inty;
	boolean internet;
    ProgressDialog authProgressDialog;
	AdView myAd;
	AdRequest adRequest;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.start);
        myAd = (AdView) findViewById(R.id.adView);
        adRequest = new AdRequest();
        adRequest.setTesting(false);
        myAd.loadAd(adRequest);


        new TheTask().execute();
        
        
    	suche = (EditText) findViewById(R.id.editText1);
		
			};

    private class TheTask extends AsyncTask<Void, Void, Void>{
    	

		@Override
        protected void onPreExecute() {
            authProgressDialog = ProgressDialog.show(main.this, "", "Loading...", true, false);
        }

        @Override
        protected Void doInBackground(Void... params) {

            
            String url="http://www.chefkoch.de";
        	suche = (EditText) findViewById(R.id.editText1);
    		try {
    			URL google = new URL("http://www.google.de");
    			InputStream inTry= (InputStream) google.getContent();
    			if (inTry.equals(null)){
    				Toast.makeText(getApplicationContext(), "Keine Internetverbindung!!!", Toast.LENGTH_LONG).show();
    				internet = false;
    			} else {
    				dailyReceipe = new DailyPreview(url,"daily");
    				internet = true;
    			}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
//				Toast.makeText(
//
//	      				getApplicationContext(),
//
//	      				e.getClass().getName() + " " + e.getMessage(),
//
//	      				Toast.LENGTH_LONG).show();
				return null;
			}
            
           if (internet){
            tr=(TableRow) findViewById(R.id.tableRow1);
            
            title= (TextView) findViewById(R.id.textView3);
            preImage = (ImageView) findViewById(R.id.imageView3);
            tr.setClickable(true);
            //WebView daily = (WebView) findViewById(R.id.webkit1);
            //daily.loadDataWithBaseURL(url, dailyReceipe.getHtmlpreview(), "text/html", "ISO-8859-1", url);
            
            tr.setOnClickListener(new View.OnClickListener() {

    	
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				Intent callActivityB = new Intent();
    				callActivityB.putExtra("url", dailyReceipe.getUrl());
    				callActivityB.putExtra("title", dailyReceipe.getTitle());
    				callActivityB.putExtra("subtitle", dailyReceipe.getSubtitle());
    				callActivityB.putExtra("image", dailyReceipe.getImage());
    				callActivityB.putExtra("imageurl", dailyReceipe.getImageurl());
    				callActivityB.putExtra("type", "daily");
    				callActivityB.setClass(main.this, Receipe.class);
    				startActivity(callActivityB);
    			}

            }	);
            
            button = (Button) findViewById(R.id.button1);
            button.setOnClickListener(new View.OnClickListener() {
    			
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				Intent callActivityB = new Intent();
    				callActivityB.putExtra("url", makeMyUrl(suche));
    				callActivityB.putExtra("count", "0");
    				
    				callActivityB.setClass(main.this, Results.class);
    				startActivity(callActivityB);
    			}
    		});
           }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            authProgressDialog.dismiss();
            if (internet){
            title.setText(dailyReceipe.getTitle());
            Log.v("recurl", dailyReceipe.getImageurl());
            preImage.setImageBitmap(dailyReceipe.getImage());
            
            } else {
            	Toast.makeText(getApplicationContext(), "Keine Internetverbindung!!!", Toast.LENGTH_LONG).show();

            }
        }
    }

//    @Override
//    public void onDestroy() {
//      myAd.destroy();
//      super.onDestroy();
//    }


    
    

    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.start_menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.open:
	        arch_intent = new Intent();
	        arch_intent.setClass(main.this, OpenArchiv.class);
	        startActivity(arch_intent);
	        return true;
	    case R.id.info:
	        showHelp();
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	} 

	private void showHelp() {
		// TODO Auto-generated method stub
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final TextView text = new TextView(this);
		text.setText(R.string.infotext);
		alert.setView(text);
		alert.setTitle("ChefKochApp Info");
		

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
						
					}
				});
		alert.show();
		
	}

	private String makeMyUrl(EditText suche) {
		// TODO Auto-generated method stub
    	String tags=suche.getText().toString().trim();
    	 String spaces = "\\s" ;
     	Pattern p = Pattern.compile(spaces);
 		Matcher m = p.matcher(tags);
 		tags = m.replaceAll("\\+");
    	String veggie=null;
    	  RadioButton radio0=(RadioButton) findViewById(R.id.radio0);    	
          RadioButton radio1=(RadioButton) findViewById(R.id.radio1);    	
          RadioButton radio2=(RadioButton) findViewById(R.id.radio2);    	
            if (radio0.isChecked()){veggie="";}
            if (radio1.isChecked()){veggie="vegetarisch";}
            if (radio2.isChecked()){veggie="vegan";}
            
           
    		String url="";
    		if (veggie.equalsIgnoreCase("vegetarisch") || veggie.equalsIgnoreCase("vegan") ){
		    	url = "http://www.chefkoch.de/rs/s0/" + tags +"+"+veggie +"/Rezepte.html";
    		}else{
		    	url = "http://www.chefkoch.de/rs/s0/" + tags +"/Rezepte.html";
    		}
		return url;
	}



}